<?php
require_once '../core/db_abstract_model.php';
require_once '../core/debug.php';
require 'messages.php';

class Articulo extends db_abstract_model{
    
    public   $nIdArticulo;
    public   $sCodebar;
    public   $sIdContabilidad;
    public   $sIdContraloria;
    public   $sNumeroSerie;
    public   $sDescripcion;
    public   $sObservaciones;
    public   $sMarca;
    public   $sModelo;
    public   $sEstado;
    public   $bActivo;
    public   $bComponente;
    private  $bCompAsignado;
    public  $nModoAdquisicion;
    public  $dFechaAdquisicion;
    public  $dFechaBaja;
    public  $nIdTipoArticulo;
    public  $nIdDepto;
    public  $nIdPersonal;
    public  $nIdProveedor;
    public  $sFactura;
    public  $nTotalFactura;
    public  $nCostoUnitario;
    public  $dFecha;
    public  $sUsuario;
    public  $sTerminal;
    
    public  $sModoAdquisicion;
    public  $sTipoArticulo;
    public  $sDepartamento;
    public  $sPersonal;
    public  $sProveedor;
    public  $simages;
    
    public function get($nIdArticulo='') {
        if (!$nIdArticulo==''){
           $this->query="SELECT * from SCIAArticulo WHERE nIdArticulo = $nIdArticulo";
           $this->get_queryresults();
           if (count($this->result_rows)==1)
               {
                foreach ($this->result_rows[0] as $propiedad=>$valor)
                    {
                        $this->$propiedad=$valor;
                    }
                    $this->getimages();
               }
           else{
                    $this->msj=MSJ_EQUIPO_FOUND;
               }
        
           }
           else{
               $this->msj=MSJ_EQUIPO_UNFOUND;
           }
    }
    
    public function set($articulo_data=array()) {
        if(array_key_exists('sIdContabilidad', $articulo_data) || array_key_exists('sIdContabilidad', $articulo_data)) {
            if(!isset($_SESSION))session_start();
        if(!$this->getduplicated($articulo_data['sIdContraloria'],$articulo_data['sIdContabilidad'])){
            foreach ($articulo_data as $campo=>$valor) {$$campo = $valor; /*echo $campo.'<br>'*/;}
            $this->query = " 
                INSERT INTO SCIAArticulo 
                (sCodeBar,sIdContabilidad,sIdContraloria,sNumeroSerie,sDescripcion,sModelo,sMarca,sObservaciones,sEstado,bActivo,bComponente,bCompAsign,
                 nModoAdquisicion,dFechaAdquisicion,dFechaBaja,nIdTipoArticulo,nIdDepto,nIdPersonal,nIdProveedor,sFactura,nTotalFactura,nCostoUnitario,
                 dFecha,sUsuario,sTerminal) 
                VALUES 
                ('','$sIdContabilidad', '$sIdContraloria', '$sNumeroSerie','$sDescripcion','$sModelo','$sMarca','$sObservaciones','$sEstado',$bActivo,$bComponente,0,
                  $nModoAdquisicion,STR_TO_DATE('$dFechaAdquisicion','%d/%m/%Y'),NULL,$nIdTipoArticulo,$nIdDepto,$nIdPersonal,$nIdProveedor,'$sFactura',CONVERT($nTotalFactura,DECIMAL),CONVERT($nCostoUnitario,DECIMAL),
                   CURRENT_TIMESTAMP,'".$_SESSION['UserName']."','".$_SESSION['IPaddress']."') 
                ";
                //if (defined(ACTIVE_DEBUG))debug($this->query);
                $this->execute_nonquery();
                $this->setbarcode($this->insertid);
                //carga el objeto recien creado
                $this->get($this->insertid);
                return TRUE;
            }
        else{
                $this->msj=MSJ_DUPLICATED_ENTRY;
                return FALSE;
            }
        }
        
   }
    
    public function edit($articulo_data=array()) {
        if(!empty($articulo_data)){
            foreach ($articulo_data as $campo=>$valor) {$$campo = $valor;}
            $this->query="UPDATE SCIAArticulo 
                SET sNumeroSerie='$sNumeroSerie',
                          sDescripcion='$sDescripcion',
                          sMarca='$sMarca',
                          sModelo='$sModelo',
                          sObservaciones='$sObservaciones',
                          sEstado='$sEstado',
                          bActivo=$bActivo,
                          nModoAdquisicion=$nModoAdquisicion,
                          nIdTipoArticulo=$nIdTipoArticulo,
                          nIdDepto=$nIdDepto,
                          nIdPersonal=$nIdPersonal,
                          nIDProveedor=$nIdProveedor,
                          nCostoUnitario=$nCostoUnitario
                      WHERE nIdArticulo = $nIdArticulo";
        ;
        $this->execute_nonquery();
        $this->setbarcode($nIdArticulo);
        }
        else{
           $this->msj=MSJ_UPDATE_ERROR;
        }
    }
    
    public function delete($nIdArticulo=''){
        if (!$nIdArticulo==''){
            $this->query="UPDATE SCIAArticulo 
                      SET bActivo=0,
                          dFechaBaja=CURRENT_TIMESTAMP
                      WHERE nIdArticulo =$nIdArticulo";
        };
    }
    
    public function getwithtext($nIdArticulo='') {
        if (!$nIdArticulo==''){
           $this->query="
               SELECT AR.* ,
                AD.sDescripcion as 'sModoAdquisicion',
                TA.sDescripcion as 'sTipoArticulo',
                DP.sDescripcion as 'sDepartamento',
                CONCAT_WS(' ',PR.sNombre,PR.sPaterno,PR.sMaterno) as 'sPersonal',
                PV.sDescripcion as 'sProveedor',
                AR.sCodeBar as sCodebar
               from SCIAArticulo  AR 
                join scicmodoadquisicion AD on (AD.nIdModoadquisicion=AR.nModoAdquisicion)
                join scictipoarticulo TA on  (TA.nidTipoArticulo=AR.nIdTipoArticulo)
                join scicdepartamento DP on  (DP.niddepartamento=AR.nIdDepto)
                join scicpersonal PR on  (PR.nidpersonal=AR.nIdpersonal)
                join scicproveedor PV on  (PV.nidproveedor=AR.nIdproveedor)
               WHERE nIdArticulo= '".$nIdArticulo."'";
           $this->get_queryresults();
           if (count($this->result_rows)==1)
               {
                foreach ($this->result_rows[0] as $propiedad=>$valor)
                    {
                        $this->$propiedad=$valor;
                    }
                    $this->getimages();
               }
           else{
                    $this->msj=MSJ_EQUIPO_FOUND;
               }
        
           }
           else{
               $this->msj=MSJ_EQUIPO_UNFOUND;
           }
    }
    
    public function gethistory($nIdArticulo='') {
        if (!$nIdArticulo==''){
           $this->query="
               SELECT AR.* ,
                AD.sDescripcion as 'sModoAdquisicion',
                TA.sDescripcion as 'sTipoArticulo',
                DP.sDescripcion as 'sDepartamento',
                CONCAT_WS(' ',PR.sNombre,PR.sPaterno,PR.sMaterno) as 'sPersonal',
                PV.sDescripcion as 'sProveedor',
                AR.sCodeBar as sCodebar
               from HSCIAArticulo  AR 
                join scicmodoadquisicion AD on (AD.nIdModoadquisicion=AR.nModoAdquisicion)
                join scictipoarticulo TA on  (TA.nidTipoArticulo=AR.nIdTipoArticulo)
                join scicdepartamento DP on  (DP.niddepartamento=AR.nIdDepto)
                join scicpersonal PR on  (PR.nidpersonal=AR.nIdpersonal)
                join scicproveedor PV on  (PV.nidproveedor=AR.nIdproveedor)
               WHERE nIdArticulo= '".$nIdArticulo."'".
               "and hnIdTipoMovSistema in (1,2)".    
               "ORDER BY hdFecha DESC";
           $this->get_queryresults();
           if (count($this->result_rows)==1)
               {
                foreach ($this->result_rows[0] as $propiedad=>$valor)
                    {
                        $this->$propiedad=$valor;
                    }
                    $this->getimages();
               }
           else{
                    $this->msj=MSJ_EQUIPO_FOUND;
               }
        
           }
           else{
               $this->msj=MSJ_EQUIPO_UNFOUND;
           }
    }
    
    public function getarticulos(){
        $this->query="SELECT nIdArticulo,sDescripcion,sIdContabilidad,sIdContraloria,sEstado from SCIAArticulo";
        $this->get_queryresults();
        $resultset=array();
        if (count($this->result_rows)>=1){
            $resultset=$this->result_rows;
        }
        else{
            $this->msj=MSJ_NO_RESULTS;
        }
        return $resultset;
    }
    
    public function getcomponents(){
        $this->query="SELECT nIdArticulo as nIdComponente,sDescripcion,sIdContabilidad,sIdContraloria,sEstado 
                        from SCIAArticulo
                       WHERE bComponente=1 and
                             bCompAsign=0";
        $this->get_queryresults();
        $resultset=array();
        if (count($this->result_rows)>=1){
            $resultset=$this->result_rows;
        }
        else{
            $this->msj=MSJ_NOCOMPN_RESULTS;
        }
        return $resultset;
    }
    
    public function getasoccomponents($nIdArticulo=''){
        $this->query="SELECT C.nIdComponente as nIdComponente ,A.sDescripcion,A.sIdContabilidad,A.sIdContraloria,A.sEstado 
                        FROM SCIAArticulo A 
                        JOIN SCIAArticuloComponentes C
                          ON (A.nIdArticulo=C.nIdComponente)
                       WHERE C.nIdArticulo=$nIdArticulo
                             and
                             C.bActivo=1";
        $this->get_queryresults();
        $resultset=array();
        if (count($this->result_rows)>=1){
            $resultset=$this->result_rows;
        }
        else{
            $this->msj=MSJ_NOCOMPN_RESULTS;
        }
        return $resultset;
    }
    
    private function getduplicated($nIdContraloria='',$nidContabilidad='') {
        $isduplicated=false;
        if(!$nIdContraloria=''){
            $this->query="SELECT * from SCIAArticulo WHERE sIdContraloria like '".$nIdContraloria."'";
            $this->get_queryresults();
            if (count($this->result_rows)==1)
            {
                $isduplicated=true;
            }
        }
        if(!$nidContabilidad=''){
            $this->query="SELECT * from SCIAArticulo WHERE sIdContabilidad like '".$nidContabilidad."'";
            $this->get_queryresults();
            if (count($this->result_rows)==1)
            {
                $isduplicated=true;
            }
        }
        return $isduplicated;
    }
    
    private function getimages(){
        if(!defined('SITE_ROOT2'))define ('SITE_ROOT2', str_replace('articulo','site_media',realpath(dirname(__FILE__))));
        $pathimages = SITE_ROOT2."\\img\\articulos\\".$this->nIdArticulo."PHOTOS\\"; // Upload directory
        if(file_exists($pathimages)){
            $imagelist=array();
           if ($handle = opendir($pathimages)) {
               while (false !== ($entry = readdir($handle))) {
                  if(preg_match("/^[0-9]+(.){1}(jpg|JPG|png|PNG|gif|GIF){1}$/",$entry))
                  {
                      array_push($imagelist, $entry);
                  }
               }
        closedir($handle);
        $this->simages=$imagelist;
          }
        }
    }
    
    private function setbarcode($nidInsertado=''){
        $endid=$nidInsertado;
        while (strlen($endid)!=5) {
            $endid='0'.$endid;
        }
        $this->getwithtext($nidInsertado); 
        $endid.="|".$this->trunc($this->sTipoArticulo)."|".$this->trunc($this->sDepartamento).
                "|".$this->trunc($this->sPersonal)."|".$this->sFactura."|".$this->sDescripcion."|";
        $this->query="Update SCIAArticulo set sCodebar='$endid' where nIdArticulo=$nidInsertado";
        $this->execute_nonquery();
    }
    
    public function setrelation($nIdArticulo,$nIdComponente){
        if(isset($nIdArticulo)&& isset($nIdComponente)){
            if(!isset($_SESSION))session_start();
            //verifica si la relacion ya existio
            $this->query="SELECT bActivo from SCIAArticuloComponentes WHERE nIdArticulo = $nIdArticulo and nIdComponente = $nIdComponente";
            $this->get_queryresults();
            if (count($this->result_rows)==1){
                $this->query="Update SCIAArticuloComponentes 
                                 set bActivo=1,
                                     dFecha=CURRENT_TIMESTAMP,
                                     sUsuario='".$_SESSION['UserName']."',
                                     sTerminal='".$_SESSION['HostName']."'
                               where nIdArticulo = $nIdArticulo 
                                     and 
                                     nIdComponente = $nIdComponente
                                     and 
                                     bActivo=0";
                $this->execute_nonquery();
            }
            else{
                
                $this->query = " 
                    INSERT INTO SCIAArticuloComponentes 
                    (nIdArticulo,nIdComponente,bActivo,bMovido,sObservacionMov,dFecha,sUsuario,sTerminal) 
                    VALUES 
                    ('$nIdArticulo','$nIdComponente',1,0,'',CURRENT_TIMESTAMP,'".$_SESSION['UserName']."','".$_SESSION['IPaddress']."')";
                $this->execute_nonquery();
            }
            
            $this->query="Update SCIAArticulo set bCompAsign=1 where nIdArticulo=$nIdComponente";
            $this->execute_nonquery();
        }
        else{
        }
    }
    
    public function unsetrelation($nIdArticulo,$nIdComponente,$sObservacionMov=''){
        if(isset($nIdArticulo)&& isset($nIdComponente)){
            if(!isset($_SESSION))session_start();
            //desasignar el articulo componente
            $this->query="Update SCIAArticulo set bCompAsign=0 where nIdArticulo=$nIdComponente and bComponente=1";
            $this->execute_nonquery();
            
            $this->query="Update SCIAArticuloComponentes 
                                 set bActivo=0,
                                     dFecha=CURRENT_TIMESTAMP,
                                     sObservacionMov='$sObservacionMov',
                                     sUsuario='".$_SESSION['UserName']."',
                                     sTerminal='".$_SESSION['HostName']."'
                               where nIdArticulo = $nIdArticulo 
                                     and 
                                     nIdComponente = $nIdComponente
                                     and 
                                     bActivo=1";
            $this->execute_nonquery();
            
        }
        else{
            
        }
    }
    
    private  function trunc($s){
        $sl=strlen($s);
        $stokens=  explode(' ',$s);
        if(count($stokens)>1){
            $stmp='';
            for ($index = 0; $index < 2; $index++) {
               $slt=strlen($stokens[$index]);
               $stmp.=substr($stokens[$index],0,-($slt-2));  
            }
            $s=$stmp;  
        }
        else{
            $sl=strlen($s);
            $s=substr($s,0,-($sl-4));  
        }
        return $s;
    }

    function __construct() {
        $this->db_name='DBSCInterno';
    }
    
    function __destruct() {
        unset($this);
    }
}
?>
